import React, { useState, useEffect } from 'react';
import { Tree, Switch, Button, Select, message } from 'antd';
import { FileOutlined, UploadOutlined } from '@ant-design/icons';
import { extractFunctions } from './parseFunctions';

const { TreeNode } = Tree;
const { Option } = Select;

export default function FileFunctionSelector() {
  const [fileList, setFileList] = useState([]);
  const [selectedFile, setSelectedFile] = useState(null);
  const [fileContent, setFileContent] = useState('');
  const [functionTreeData, setFunctionTreeData] = useState([]);
  const [checkAll, setCheckAll] = useState(false);
  const [selectedFunctionKeys, setSelectedFunctionKeys] = useState([]);
  const [loading, setLoading] = useState(false);

  // 处理文件选择
  const handleFileSelect = (file) => {
    // 验证文件类型
    const validExtensions = ['.c', '.h', '.cpp', '.hpp', '.cc', '.cxx'];
    const fileExt = file.name.split('.').pop().toLowerCase();
    
    if (!validExtensions.includes('.' + fileExt)) {
      message.error('请选择C/C++文件(.c, .h, .cpp, .hpp, .cc, .cxx)');
      return;
    }

    setSelectedFile(file);
    setLoading(true);
    
    const reader = new FileReader();
    reader.onload = (e) => {
      setFileContent(e.target.result);
      setLoading(false);
    };
    reader.onerror = () => {
      message.error('读取文件失败');
      setLoading(false);
    };
    reader.readAsText(file);
  };

  // 解析文件内容中的函数
  useEffect(() => {
    if (fileContent && selectedFile) {
      const functions = extractFunctions(fileContent).map(func => ({
        title: func,
        key: func
      }));
      setFunctionTreeData(functions);
      setCheckAll(false);
      setSelectedFunctionKeys([]);
    }
  }, [fileContent, selectedFile]);

  // 全选切换
  const handleCheckAllChange = (checked) => {
    setCheckAll(checked);
    setSelectedFunctionKeys(checked ? functionTreeData.map(item => item.key) : []);
  };

  // 单个函数勾选
  const handleFunctionCheck = (checkedKeys) => {
    setSelectedFunctionKeys(checkedKeys);
    setCheckAll(checkedKeys.length === functionTreeData.length);
  };

  // 生成测试点击
  const handleGenerateTest = () => {
    if (!selectedFile || selectedFunctionKeys.length === 0) {
      message.warning('请选择至少一个函数');
      return;
    }
    message.success(`已为 ${selectedFunctionKeys.length} 个函数生成测试`);
    console.log('生成测试:', {
      fileName: selectedFile.name,
      functions: selectedFunctionKeys
    });
  };

  return (
    <div style={{ width: 400, margin: '20px auto' }}>
      {/* 文件上传 */}
      <div style={{ marginBottom: 20 }}>
        <h3>1. 选择文件</h3>
        <Button
          icon={<UploadOutlined />}
          onClick={() => document.getElementById('file-upload').click()}
          loading={loading}
        >
          选择文件(.c/.h/.cpp/.hpp)
        </Button>
        <input
          id="file-upload"
          type="file"
          accept=".c,.h,.cpp,.hpp,.cc,.cxx"
          style={{ display: 'none' }}
          onChange={(e) => {
            if (e.target.files.length > 0) {
              const file = e.target.files[0];
              setFileList([file]);
              handleFileSelect(file);
            }
          }}
        />
        {selectedFile && (
          <div style={{ marginTop: 10 }}>
            已选择: {selectedFile.name}
          </div>
        )}
      </div>

      {/* 函数选择 - 始终显示 */}
      <div>
        <h3>2. 为{selectedFile ? `${selectedFile.name}` : ''}选择函数</h3>
        {!selectedFile ? (
          <div style={{ color: '#999', marginBottom: 20 }}>
            请先选择C/C++文件以查看函数列表
          </div>
        ) : (
          <>
            <div style={{ display: 'flex', alignItems: 'center', marginBottom: 10 }}>
              <Switch
                checked={checkAll}
                onChange={handleCheckAllChange}
                style={{ marginRight: 10 }}
                disabled={functionTreeData.length === 0}
              />
              <span>全选 ({functionTreeData.length})</span>
              <Button
                type="primary"
                onClick={handleGenerateTest}
                style={{ marginLeft: 'auto' }}
                disabled={functionTreeData.length === 0 || selectedFunctionKeys.length === 0}
              >
                生成测试 ({selectedFunctionKeys.length})
              </Button>
            </div>
            {functionTreeData.length > 0 ? (
              <Tree
                checkable
                defaultExpandAll
                onCheck={handleFunctionCheck}
                checkedKeys={selectedFunctionKeys}
              >
                {functionTreeData.map((item) => (
                  <TreeNode 
                    title={item.title} 
                    key={item.key} 
                    icon={<FileOutlined />} 
                  />
                ))}
              </Tree>
            ) : (
              <div style={{ color: '#999' }}>
                未在文件中找到函数定义
              </div>
            )}
          </>
        )}
      </div>
    </div>
  );
}